﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections;
using System.Web.UI.WebControls;
using System.Data;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{

    #region "Old Ref"

    #endregion

    public partial class Resumption_Duty_Print : LayoutsPageBase
    {
        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();


        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string ResumpRequestNo;
        public static string SourceLstName;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;
        public static string lstGuid { get; set; }
        public string camlQry { get; set; }
        public static string Mode { get; set; }
        public static string submittedfor { get; set; }
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList { get; set; }
        string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string LeaveRefID;
        public static string refID;
        private static bool Submit = false;

        public static int ResumpItemID;


        object[] ResumptionParams;

        private static SPListItemCollection oItemsColl = null;
        public static SPListItem oItems = null;

        public static string RequestType = null;

        string[] buttonVisibilty = new string[5];


        #endregion


        public Resumption_Duty_Print()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Resumption of Duty Forms";
            TaskLstName = "Resumption of Duty Tasks";
            CmntsLstName = "Resumption of Duty Comments";
            SourceLstName = "Leave Request Forms";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    Submit = false;
                    Mode = Request.QueryString["Mode"];
                    refID = Request.QueryString["RefID"]; // From Dashboard.
                    LeaveRefID = Request.QueryString["LeaveRefID"]; // From Dashboard.

                    if (Mode == "Print" || Mode == "View")
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            ReLoadDetails();
                            GetUserInfo();
                            pplReqUser.Enabled = false;

                        });
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "Page_Load";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        private void GetUserInfo()
        {

            if (LeaveRefID != null)
            {
                GetLeaveUser(pplReqUser);
            }

            else if (pplReqUser.ResolvedEntities.Count > 0)
            {
                PickerEntity pe = (PickerEntity)pplReqUser.Entities[0];
                string submittedFor = pe.DisplayText;
                camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + submittedFor + "</Value></Eq><Eq>" +
                    "<FieldRef Name=\"ResumptionStatus\" /><Value Type=\"Text\">No</Value></Eq></And></Where>";
                oItems = obj.GetSPListItem(SiteURL, SourceLstName, camlQry);
                if (oItems != null)
                {
                    if (!CheckEntryForm(Convert.ToString(oItems["Reference_x0020_Number"]))) { SetControlsValue(oItems); }
                }

            }
        }


        private bool CheckEntryForm(string LeaverefID)
        {
            bool ckResStatus = false;
            try
            {
                SPQuery qry = new SPQuery();
                camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaverefID + "</Value></Eq></Where>";
                qry.Query = camlQry;
                qry.ViewFields = "<FieldRef Name='LeaveReferenceNo' />";
                SPListItem oItem = obj.GetSPListItem(SiteURL, MainLstName, qry);
                if (oItem != null)
                    ckResStatus = true;
                else
                    ckResStatus = false;

            }
            catch (Exception ex)
            {
                // GenerateExceptionLog("Leave_Request_DashboardUserControl : ", ex.Message, "CheckResumption");
            }
            return ckResStatus;
        }



        private void GetLeaveUser(PeopleEditor ppls)
        {
            ArrayList _arrayList = new ArrayList();

            SPFieldUserValue fldUser = null;
            SPQuery qry = new SPQuery();
            camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";
            qry.Query = camlQry;
            //qry.ViewFields = "<FieldRef Name='SubmittedFor' />";
            oItems = obj.GetSPListItem(SiteURL, SourceLstName, qry);
            if (oItems != null)
            {
                fldUser = new SPFieldUserValue(SPContext.Current.Web, Convert.ToString(oItems["SubmittedFor"]));

                PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                _pickerEntity.Key = fldUser.LookupValue;
                _pickerEntity.IsResolved = true;
                _arrayList.Add(_pickerEntity);
                ppls.UpdateEntities(_arrayList);
                SetControlsValue(oItems);
                submittedfor = fldUser.LookupValue;
                lblReqUser.Text = fldUser.LookupValue;
            }
            else
            {

            }
        }

        private void SetControlsValue(SPListItem oItems)
        {
            txtReqEmpId.Text = Convert.ToString(oItems["EmployeeID"]);
            txtReqDivision.Text = Convert.ToString(oItems["Division"]);
            txtReqDepartment.Text = Convert.ToString(oItems["Department"]);
            txtReqDesignation.Text = Convert.ToString(oItems["Designation"]);
            txtPastportNo.Text = Convert.ToString(oItems["PassportNo"]);

            if (string.IsNullOrEmpty(Convert.ToString(oItems["LeaveOthers"])))
                txtLeaveType.Text = Convert.ToString(oItems["LeaveType"]);
            else
                txtLeaveType.Text = Convert.ToString(oItems["LeaveType"]) + " - " + Convert.ToString(oItems["LeaveOthers"]);

            txtLeaveType.Text = Convert.ToString(oItems["LeaveType"]);
            dtTravelDt.Text = Convert.ToDateTime(oItems["TravelDate"]).ToString("dd/MM/yyyy");
            dtReturnDt.Text = Convert.ToDateTime(oItems["ReturnDate"]).ToString("dd/MM/yyyy");
            lblLevReqNo.Text = Convert.ToString(oItems["Reference_x0020_Number"]);
            dtLeaveReqDate.Text = Convert.ToDateTime(oItems["RequestDate"]).ToString("dd/MM/yyyy");
        }


        private void cntrls(params object[] parameter)
        {
            ResumptionParams = parameter;
        }


        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {

                if (refID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";
                if (LeaveRefID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";

                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {
                    string RefNo = Convert.ToString(lstDatas["Reference Number"]);
                    lblResumpReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtpDate.Text = Convert.ToDateTime(lstDatas["RequestDate"]).ToString("dd/MM/yyyy");
                    LeaveRefID = Convert.ToString(lstDatas["LeaveReferenceNo"]);
                    txtExcessLeaveDays.Text = Convert.ToString(lstDatas["ExcessLeaveDays"]);
                    txtAction.Text = Convert.ToString(lstDatas["Action"]);
                    dtResumptionDt.Text = Convert.ToDateTime(lstDatas["ResumptionDate"]).ToString("dd/MM/yyyy");
                    dtLeaveReqDate.Text = Convert.ToDateTime(lstDatas["LeaveRequestDate"]).ToString("dd/MM/yyyy");

                    ResumpItemID = Convert.ToInt32(lstDatas["ID"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["Handedover"])))
                    {
                        lblconfirm.Text = "Yes";
                        dtHandoverDt.Text = Convert.ToDateTime(lstDatas["HandoverDate"]).ToString("dd/MM/yyyy");
                    }
                    else
                    {
                        lblconfirm.Text = "No";
                    }

                    GetApprovedUsers(RefNo);
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion

        private void GetApprovedUsers(string refNo)
        {
            SPListItemCollection oItemColl = null;
            string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
            oItemColl = obj.GetSPListItems(SiteURL, TaskLstName, camlQry);
            DataTable dt = new DataTable();
            // dt.Columns.Add("Approved By");
            DataRow dr;

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem oItem in oItemColl)
                        {
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                            dt.Columns.Add(oItem["ID"].ToString());
                        }

                        dr = dt.NewRow();
                        int wfCnt = dt.Columns.Count;
                        int i = 0;
                        foreach (SPListItem oItem in oItemColl)
                        {
                            if (i < wfCnt)
                            {
                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                if (Convert.ToString(fldUser.LookupValue).Contains("\\"))
                                {
                                    string user = Convert.ToString(fldUser.LookupValue);
                                    string[] users = user.Split('\\');
                                    int arrLenth = users.Length;
                                    if (arrLenth > 0)
                                        dr[i] = users[1];
                                    else
                                        dr[i] = users[0];
                                }
                                i++;
                            }
                        }
                        dt.Rows.Add(dr);
                        i = 0;
                        dr = dt.NewRow();
                        while (i < wfCnt)
                        {
                            dr[i] = "Approved By";
                            i++;
                        }
                        dt.Rows.Add(dr);
                        gvApprovers.DataSource = dt;
                        gvApprovers.DataBind();
                        gvApprovers.HeaderRow.Visible = false;
                    }

                }

            }

        }

    }
}
